package com.yy.main.app.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.collections.YYListKits;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.object.YYObjectKits;
import com.yy.kit.string.YYStrKits;
import com.yy.main.app.mapper.TKeywordMapper;
import com.yy.main.app.service.IKeywordMessageService;
import com.yy.main.app.service.IKeywordService;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 关键字表，关键字发送消息的时候，区分关键字做相应操作 前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017-09-20
 */
@Controller
@RequestMapping("/keyword")
@Api(value = "关键字controller", tags = {"关键字controller"})
public class KeywordController extends CommonController {

    @Resource(name = "iKeywordService")
    private IKeywordService iKeywordService;
    @Resource(name = "iKeywordMessageService")
    private IKeywordMessageService iKeywordMessageService;
    @Autowired
    private TKeywordMapper tKeywordMapper;


    /**
     * <p>
     * 跳转到关键字管理页面
     * </p>
     *
     * @param session {@link HttpSession}
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/keywordList", method = RequestMethod.GET)
    @HasPers(name = "keyword:manager")
    @ApiOperation(value = "跳转到关键字管理页面", httpMethod = "GET", notes = "跳转到关键字管理页面,需要keyword:manager权限")
    public ModelAndView keywordList(HttpSession session) {
        return goToPageByModelAndView("system/keyword/keyword_list", null, getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 保存关键字信息
     * </p>
     *
     * @param key   关键字实体
     * @param msgid 关键字要关联的消息
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月21日
     */
    @ApiOperation(value = "保存关键字信息", httpMethod = "POST", notes = "增加或修改关键字")
    @RequestMapping(value = "/savekeyword", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> savekeyword(TKeyword key, String msgid) {
        return iKeywordService.savekeyword(key, msgid);
    }

    /**
     * <p>
     * 修改关键字中消息的顺序
     * </p>
     *
     * @param id    消息id
     * @param keyid 关键字id
     * @param seq   顺序
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月25日
     */
    @RequestMapping(value = "/updateMsgSeq", method = RequestMethod.POST)
    @ApiOperation(value = "修改关键字中消息的顺序", httpMethod = "POST", notes = "修改关键字中消息的顺序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "消息ID", required = true),
            @ApiImplicitParam(name = "seq", value = "顺序", required = true),
            @ApiImplicitParam(name = "keyid", value = "关键字id", required = true)
    })
    public @ResponseBody
    Map<String, Object> updateMsgSeq(String id, Integer seq, String keyid) {
        TKeywordMessage km = new TKeywordMessage();
        km.setSeq(seq);

        TKeywordMessageExample example = new TKeywordMessageExample();
        example.createCriteria()
                .andMessage_idEqualTo(id)
                .andKeyword_idEqualTo(keyid);

        int b = iKeywordMessageService.updateByExample(km, example);
        if (b > 0) {
            return successMap("修改成功!");
        } else {
            return errorMap("修改失败,请重试!");
        }
    }

    /**
     * <p>
     * 跳转到编辑关键字的页面
     * </p>
     *
     * @param id 关键字ID
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/keywordform/{id}", method = RequestMethod.GET)
    @HasPers(name = "keyword:add,keyword:update")
    @ApiOperation(value = "跳转到编辑关键字的页面", httpMethod = "GET", notes = "跳转到编辑关键字的页面,需要keyword:add,keyword:update权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "关键字ID", required = true, paramType = "form")})
    public ModelAndView keywordForm(@PathVariable("id") String id, HttpServletRequest request) {
        // 如果是新增id肯定是-1
        TKeyword word = iKeywordService.selectById(id);

        // 查询出与关键字关联的消息列表
        List<TMessage> previewList = iKeywordService.selectMessageByKeywordId(id);

        // 查询出与关键字关联的消息的消息字符串1,2,3
        TKeywordMessageExample example = new TKeywordMessageExample();
        example.createCriteria().andKeyword_idEqualTo(id);
        List<TKeywordMessage> kmList = iKeywordMessageService.selectListByExample(example);

        if (YYObjectKits.isNull(word)) {
            word = new TKeyword();
            word.setId("-1");
        }
        if (YYListKits.isEmpty(previewList)) {
            previewList = YYListKits.createList();
        }

        StringBuilder msgids = new StringBuilder();

        for (int i = 0; i < kmList.size(); i++) {
            TKeywordMessage km = kmList.get(i);
            if (i > 0) {
                msgids.append(",");
            }
            msgids.append(km.getMessage_id());
        }
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("keyword", word);
        param.put("previewList", previewList);
        param.put("msgid", msgids.toString());
        return goToPageByModelAndView("system/keyword/keyword_form", param, getCurrentUser(request.getSession()).getId());
    }

    /**
     * <p>
     * 获得管理端关键字的数据表格
     * </p>
     *
     * @param page    当前页
     * @param limit   每页显示多少条数据
     * @param title   关键字标题
     * @param keycode 关键字KEY，唯一标识
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/keywordTable", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "关键字标题", paramType = "query"),
            @ApiImplicitParam(name = "keycode", value = "关键字key，唯一标识", paramType = "query")
    })
    @ResponseBody
    public Map<String, Object> keywordTable(Integer page, Integer limit, String title, String keycode) {
        TKeywordExample example = new TKeywordExample();
        TKeywordExample.Criteria criteria = example.createCriteria();

        if (YYStrKits.isNotBlank(title)) {
            criteria.andTitleLike(YYStrKits.like(title));
        }

        if (YYStrKits.isNotBlank(keycode)) {
            criteria.andKeycodeLike(YYStrKits.like(keycode));
        }

        PageHelper.startPage(page, limit);
        List<TKeyword> list = tKeywordMapper.selectByExample(example);
        PageInfo info = new PageInfo(list);
        return super.pageToMap(info);
    }

    /**
     * <p>
     * 删除关键字
     * </p>
     *
     * @param id 关键字id
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/delkeyword/{id}", method = RequestMethod.POST)
    @HasPers(name = "keyword:delete")
    @ApiOperation(value = "删除关键字", httpMethod = "POST", notes = "删除关键字,需要keyword:delete权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "关键字ID", required = true, paramType = "form")})
    public @ResponseBody
    Map<String, Object> delkeyword(@PathVariable("id") String id) {
        return iKeywordService.delkeyword(id);
    }

    /**
     * <p>
     * 查看关键字详情
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
    @HasPers(name = "keyword:show")
    @ApiOperation(value = "查看关键字详情", httpMethod = "GET", notes = "查看关键字详情,需要keyword:show权限")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "关键字ID", required = true, paramType = "form")})
    public ModelAndView show(@PathVariable("id") String id) {
        TKeyword keyword = iKeywordService.selectById(id);
        Map<String, Object> param = YYMapKits.createHashMap();

        // 查询出与关键字关联的消息列表
        List<TMessage> previewList = iKeywordService.selectMessageByKeywordId(id);
        if (YYListKits.isEmpty(previewList)) {
            previewList = YYListKits.createList();
        }

        param.put("previewList", previewList);
        param.put("keyword", keyword);
        return goToPageByModelAndView("system/keyword/keyword_show", param);
    }

    /**
     * <p>
     * 从关键字中移除消息
     * <p>
     *
     * @param keyid 关键字id
     * @param msgid 消息id
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    @RequestMapping(value = "/removeMessagesFromKeywords/{keyid}/{msgid}", method = RequestMethod.POST)
    @ApiOperation(value = "从关键字中移除消息", httpMethod = "POST", notes = "从关键字中移除消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyid", value = "关键字ID", paramType = "form"),
            @ApiImplicitParam(name = "msgid", value = "消息ID", paramType = "form")
    })
    @ResponseBody
    public Map<String, Object> removeMessagesFromKeywords(
            @PathVariable(value = "keyid") String keyid, @PathVariable(value = "msgid") String msgid) {
        TKeywordMessageExample example = new TKeywordMessageExample();
        example.createCriteria()
                .andKeyword_idEqualTo(keyid)
                .andMessage_idEqualTo(msgid);

        Integer b = iKeywordMessageService.deleteByExample(example);
        if (b > 0) {
            return successMap("移除成功!");
        } else {
            return errorMap("移除失败,请重试!");
        }
    }

    /**
     * <p>
     * 根据关键字id查询出与之相关联的消息列表
     * </p>
     *
     * @param keywordid 关键字id
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    @RequestMapping(value = "/selectMessageByKeywordId", method = RequestMethod.GET)
    @ApiOperation(value = "根据关键字id查询出与之相关联的消息列表", httpMethod = "GET", notes = "根据关键字id查询出与之相关联的消息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true),
            @ApiImplicitParam(name = "keywordid", value = "关键字id")
    })
    @ResponseBody
    public Map<String, Object> selectMessageByKeywordId(Integer page, Integer limit, String keywordid) {
        return super.pageToMap(iKeywordService.selectMessageByKeywordId(page, limit, keywordid));
    }

}
